package com.scuec.groupfive.controller;

import com.scuec.groupfive.entity.FavoriteFolder;
import com.scuec.groupfive.entity.Questions;
import com.scuec.groupfive.service.FavoriteFolderService_z;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.springframework.http.HttpStatus;
import java.util.ArrayList;
import com.scuec.groupfive.mapper.FavoriteFolderMapper_z;

@RestController
@RequestMapping("/api/favorites")
@CrossOrigin
public class FavoriteFolderController_z {
    @Resource
    private FavoriteFolderService_z favoriteFolderService_z;

    @Resource
    private FavoriteFolderMapper_z favoriteFolderMapper_z;

    @GetMapping("/folders")
    public ResponseEntity<List<FavoriteFolder>> getFolders(@RequestParam Long userId) {
        List<FavoriteFolder> folders = favoriteFolderService_z.getFoldersByUserId(userId);
        return ResponseEntity.ok(folders);
    }

    @PostMapping("/folders")
    public ResponseEntity<FavoriteFolder> createFolder(@RequestBody FavoriteFolder folder) {
        FavoriteFolder createdFolder = favoriteFolderService_z.createFolder(folder);
        return ResponseEntity.ok(createdFolder);
    }

    @PutMapping("/folders/{id}")
    public ResponseEntity<FavoriteFolder> updateFolder(
            @PathVariable Long id,
            @RequestBody Map<String, String> request) {
        // 先获取收藏夹信息
        List<FavoriteFolder> folders = favoriteFolderService_z.getFoldersByUserId(null);
        FavoriteFolder existingFolder = folders.stream()
                .filter(f -> f.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("收藏夹不存在"));

        // 更新收藏夹信息
        FavoriteFolder folder = new FavoriteFolder();
        folder.setId(id);
        folder.setName(request.get("name"));
        folder.setUserId(existingFolder.getUserId());
        folder.setDescription(existingFolder.getDescription());

        FavoriteFolder updatedFolder = favoriteFolderService_z.updateFolder(folder);
        return ResponseEntity.ok(updatedFolder);
    }

    @GetMapping("/questions")
    public ResponseEntity<Map<String, Object>> getFavoriteQuestions(
            @RequestParam Long userId,
            @RequestParam(required = false) Long folderId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String examType,
            @RequestParam(required = false) String questionType,
            @RequestParam(required = false) String subjectId) {

        // 计算偏移量
        Integer offset = (page - 1) * pageSize;

        // 获取题目列表
        List<Questions> questions = favoriteFolderService_z.getQuestionsByContent(
                userId, folderId, examType, questionType, subjectId, offset, pageSize);

        // 获取总数
        Integer total = favoriteFolderService_z.countQuestions(
                userId, folderId, examType, questionType, subjectId);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", questions);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return ResponseEntity.ok(result);
    }

    @GetMapping("/folders/{folderId}/questions")
    public ResponseEntity<Map<String, Object>> getFolderQuestions(
            @PathVariable Long folderId,
            @RequestParam Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String examType,
            @RequestParam(required = false) String questionType,
            @RequestParam(required = false) String subjectId) {

        // 计算偏移量
        Integer offset = (page - 1) * pageSize;

        // 获取题目列表
        List<Questions> questions = favoriteFolderService_z.getQuestionsByContent(
                userId, folderId, examType, questionType, subjectId, offset, pageSize);

        // 获取总数
        Integer total = favoriteFolderService_z.countQuestions(
                userId, folderId, examType, questionType, subjectId);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", questions);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return ResponseEntity.ok(result);
    }

    @PostMapping("/folders/{folderId}/questions/{questionId}")
    public ResponseEntity<Void> addQuestionToFolder(
            @PathVariable Long folderId,
            @PathVariable Long questionId,
            @RequestBody Map<String, Long> request) {
        Long userId = request.get("userId");
        favoriteFolderService_z.addQuestionToFolder(userId, questionId, folderId);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/folders/move")
    public ResponseEntity<Void> moveQuestion(@RequestBody Map<String, Long> request) {
        Long userId = request.get("userId");
        Long questionId = request.get("questionId");
        Long folderId = request.get("folderId");

        favoriteFolderService_z.moveQuestion(userId, questionId, folderId);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/questions/{questionId}")
    public ResponseEntity<?> deleteFavorite(@PathVariable Long questionId, @RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            favoriteFolderService_z.deleteQuestionFromFolder(userId, questionId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "取消收藏成功");
            return ResponseEntity.ok().body(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "取消收藏失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/difficulty-levels")
    public ResponseEntity<List<Map<String, Object>>> getDifficultyLevels() {
        List<Map<String, Object>> levels = favoriteFolderMapper_z.getDifficultyLevels();
        return ResponseEntity.ok(levels);
    }
}